package com.huawei.crm.job;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;

import java.time.DayOfWeek;
import java.util.concurrent.TimeUnit;

public class JobUtil {

	public static String getDayCron(String time, String pattern) {
		DateTime dateTime = DateUtil.parse(time, pattern);
		return getCronExpression(dateTime, "*", "*", "?");
	}

	public static String getWeekCron(String dayOfWeek, String time, String pattern) {
		int value = DayOfWeek.valueOf(dayOfWeek).getValue();
		return getWeekCron(value, time ,pattern);
	}

	public static String getWeekCron(int dayOfWeek, String time, String pattern) {
		DateTime dateTime = DateUtil.parse(time, pattern);
		return getCronExpression(dateTime, "?", "*", String.valueOf(dayOfWeek));
	}

	public static String getMonthCron(String dayOfMonth, String time, String pattern) {
		DateTime dateTime = DateUtil.parse(time, pattern);
		return getCronExpression(dateTime, dayOfMonth, "*", "*");
	}

	public static String getMonthCron(int dayOfMonth, String time, String pattern) {
		return getMonthCron(String.valueOf(dayOfMonth), time, pattern);
	}

	public static String getYearCron(int month, int dayOfMonth, String time, String pattern) {
		DateTime dateTime = DateUtil.parse(time, pattern);
		return getCronExpression(dateTime, String.valueOf(dayOfMonth), String.valueOf(month), "?");
	}

	public static String getCronExpression(DateTime dateTime, String dayOfMonth, String month, String dayOfWeek) {
		int second = dateTime.second();
		int minute = dateTime.minute();
		int hour = dateTime.hour(true);
		return String.format("%02d %02d %02d %s %s %s", second, minute, hour, dayOfMonth, month, dayOfWeek);
	}

	public static String getHourCron(int minute) {
		return String.format("%02d %02d %s %s %s %s", 0, minute, "*", "*", "*", "?");
	}

	public static int getInterval(int interval, TimeUnit timeUnit) {
		switch (timeUnit) {
			case DAYS:
				return interval * 24 * 60 * 60 * 1000;
			case HOURS:
				return interval * 60 * 60 * 1000;
			case MINUTES:
				return interval * 60 * 1000;
			case SECONDS:
				return interval * 1000;
		}
		return 0;
	}

	public static void main(String[] args) {
		// 每天
		System.out.println(getDayCron("12:00", "HH:mm"));
		// 每周
		System.out.println(getWeekCron("MONDAY", "12:00", "HH:mm"));
		System.out.println(getWeekCron(1, "12:00", "HH:mm"));
		// 每月
		System.out.println(getMonthCron("L", "12:00", "HH:mm"));
		System.out.println(getMonthCron(1, "12:00", "HH:mm"));
		// 每年
		System.out.println(getYearCron(1,1, "12:00", "HH:mm"));
		// 每小时
		System.out.println(getHourCron(12));

	}
}
